package com.tuling.jucdemo.jmm;

import com.tuling.jucdemo.factory.UnsafeFactory;

public class ReOrderTest {
    private static int x = 0,y = 0;
    private static int a = 0,b = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        while(true){
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            /**
             * x,y: 00,01,10,11
             */
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    shortWait(2000);
                    a = 1; // volatile写
                    // storeLoad JMM内存屏障
                    // UnsafeFactory.getUnsafe().storeFence();
                    x = b; // volatile读
                }
            });

            Thread t2 = new Thread(new Runnable(){
                @Override
                public void run() {
                    UnsafeFactory.getUnsafe().storeFence();
                    b = 1;
                    y = a;
                }
            });

            t1.start();
            t2.start();
            t1.join();
            t2.join();

            System.out.println("第" + i + "次("+x+","+y+")");
            if(x==0 && y==0){
                break;
            }
        }
    }

    public static void shortWait(long interval ){
        long start = System.currentTimeMillis();
        long end;
        do{
            end = System.nanoTime();
        }while(start + interval >= end);
    }
}

